package cn.jh.common.utils;

import cn.jh.common.core.base.UrlKt;
import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class TokenUtil {

    private static final Logger LOG = LoggerFactory.getLogger(TokenUtil.class);

    public static String createToken(long userId, long brandId, String phone) {
        String userToken = Jwts.builder()
                .setSubject("JuHei")
                .setExpiration(new Date(new Date().getTime() + 1000L * 60 * 60 * 24 * 600))
                .claim("userId", userId)
                .claim("brandId", brandId)
                .claim("phone", phone)
                .signWith(SignatureAlgorithm.HS512, CommonConstants.SECRETKEY).compact();

        return userToken;
    }

    public static long getUserId(String token) {
        ImmutableMap<String, Object> claims = getClaims(token);
        if (claims.isEmpty()) {
            // 很多接口把 token 直接放在 URL 上，很容易出现问题，这里多加一步 URL 解码
            claims = getClaims(UrlKt.decode(token, StandardCharsets.UTF_8));
        }
        return ((Number) claims.getOrDefault("userId", 0L)).longValue();
    }

    public static String getUserPhone(String token) {

        Claims claims = Jwts.parser().setSigningKey(CommonConstants.SECRETKEY).parseClaimsJws(token).getBody();
        return (String) claims.get("phone");
    }

    /**
     * @deprecated use new method {@link #getBrandId(String)}
     */
    public static long getBrandid(String token) {
        return getBrandId(token);
    }

    /**
     * 获取 token 中的{@code brandId}，如果未登录，或者token无效，则返回 0。
     */
    public static long getBrandId(String token) {
        Map<String, Object> claims = getClaims(token);
        if (claims.isEmpty()) {
            claims = getClaims(UrlKt.decode(token, StandardCharsets.UTF_8));
        }
        return ((Number) claims.getOrDefault("brandId", 0L)).longValue();
    }

    public static ImmutableMap<String, Object> getClaims(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(CommonConstants.SECRETKEY)
                    .parseClaimsJws(token).getBody();
            String phone = (String) claims.getOrDefault("phone", "");
            long brandId = ((Number) claims.getOrDefault("brandId", 0L)).longValue();
            long userId = ((Number) claims.getOrDefault("userId", 0L)).longValue();
            return ImmutableMap.of(
                    "userId", userId,
                    "brandId", brandId,
                    "phone", phone
            );
        } catch (Exception ex) {
            // token invalid
            return ImmutableMap.of();
        }
    }

    /**
     * 验证token
     */
    public static Object validToken(String token) throws Exception {

        Map map = new HashMap();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }

        return userId;

    }


}
